<?php


namespace Lib\Component;



class Factory
{
    private static $instance = null;
    private $instances = array();

    private function __construct() {
    }

    /**
     * 获取工厂实例
     * @return Factory|null
     */
    public static function getFactory()
    {
        if (self::$instance == null) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 通过工厂获取对象
     * @param $className
     * @return mixed|null
     * @throws \ReflectionException
     */
    public function get($className)
    {
        if (isset($this->instances[$className]) && $this->instances[$className] != null) {
            return $this->instances[$className];
        }
        return $this->instantiate($className);
    }

    /**
     * 实例化对象
     * @param $className
     * @return mixed|null
     * @throws \ReflectionException
     */
    private function instantiate($className)
    {
        if (!class_exists($className)) {
            return null;
        }

        // 通过反射获取实现接口，判断实例化方式
        $rc1 = new \ReflectionClass($className);
        if (in_array(ComponentInterface::class, array_keys($rc1->getInterfaces()))) {
            $this->instances[$className] = $className::getInstance();
        } else {
            $this->instances[$className] = new $className();
        }
        // $this->instances[$className] = $className::getInstance();
        return $this->instances[$className];
    }
}